<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/11/23
 * Time: 下午8:35
 */

namespace Api\Controller;

use Mobile\Controller\WechatController;
use Mobile\Model\articleModel;
use Mobile\Model\articletypeModel;
use Mobile\Model\goodsModel;

class ThirdController extends LoginBaseController
{
    public $articleModel;
    public $wechat;
    public $articletypeModel;
    public $goodsModel;
    public function __construct()
    {
        C('VIEW_PATH','./Theme/mobile/');//模板文件目录
        /**
         * 推广:/mobile/qrcode/index
        如何赚钱 /mobile/index/makemoney
        我要开店：/mobile/goods/daili
         */
        parent::__construct();
        $this->articleModel = new articleModel();
        $this->articletypeModel = new articletypeModel();
        $this->wechat=new WechatController(array());
        $this->goodsModel = new goodsModel();
    }

    //申请加盟
    public function jiameng () {
        $seo = array(
            'title' => '申请代理'
        );
        $this->setSeo($seo);
        //dump($this->member);die;
        $min = $this->member['grade_id']>=5?6:5;
        $where = array(
            'grade_id' => array('between',array($min,6))
        );
        $gradeArr = M('grade')->where($where)->select();
        $this->assign('gradeArr',$gradeArr);
        //dump($gradeArr);die;
        $this->display('Mobile@Cart:jiameng');
    }


    //商学院
    public function lists() {
        $page = get("p",1);
        $atype_id = get('atype_id');
        //文章
        $where = array(
            "status" => 1,
            'uid' => 0,//管理员发布
            "post_time" => array("elt",date("Y-m-d H:i:s")),
            "is_check" => 1,
        );
        $title = get("title","");
        if(trim($title) != ""){
            $where["title"] = array("like","%{$title}%");
        }
        if($atype_id){
            $where["atype_id"] = $atype_id;
        }
        $article_list = $this->articleModel->getArticleList($where, $page);
        if(IS_AJAX){
            exit_json($article_list);
        }
        $this->assign('datalist',$article_list);
        $count = $this->articleModel->getArticleCount($where);
        $totalpage = ceil($count/C('PAGE_SIZE'));
        $this->assign('totalpage',$totalpage);


        $typelist = array(
            $this->articletypeModel->order('atype_ord')->page(1,3)->select(),
            $this->articletypeModel->order('atype_ord')->page(2,3)->select(),
        );
        $this->assign('typelist',$typelist);


        C("SITE_NAME",'商学院');
        /*
         * 设置分享信息
         */
        $share_data = array(
            "title" => C("SITE_NAME"),
        );
        $this->setShare($share_data);


        /*
         * 设置标题
        */
        $seo_data = array(
            "title" => C("SITE_NAME"),
            "keywords" => "",
            "description" => "",
        );
        $this->setSeo($seo_data);

        $this->display('Mobile@Article:kecheng');
    }
    /*
        * 我的二维码
        */
    public function myqrcode(){

        $seo_data = array(
            "title" => $this->lang['user_qrcode'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);

        $share_data = array(
            "title" => $this->member['nickname']."的微商城",
        );
        $this->setShare($share_data);

        if($this->member['grade_id']<=1) {
            $this->error2('请先成为代理');
        }

        $userinfo = $this->member;
        //获取用户信息
        $wxuser = $this->wechat->getUserInfo($userinfo['openid']);

        if(!empty($wxuser)){
            $userinfo['nickname'] = $wxuser['nickname'] ? $wxuser['nickname'] : $userinfo['nickname'];
            $userinfo['headimgurl'] = $wxuser['headimgurl'] ? $wxuser['headimgurl'] : $userinfo['headimgurl'];
        }

        $share_pic = $this->makeshare($userinfo,1);//生成分享二维码
        if($share_pic){
            $this->assign("share_pic",$share_pic);
        }

        $this->display('Mobile@Qrcode:index');
    }


   //我要开店
    public function daili(){
        $seo_data = array(
            "title" => "我要开店",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);

        $page = get("p",1);
        $where = array(
            'goods_id' => array('in',array(2,3))
        );

        $goods_list = $this->goodsModel->getGoodsList($where, $page);
        $g = array();

        //等级价格
        $grade_id = $this->member['grade_id'];
        $grade_id = $grade_id ? $grade_id : 0;

        foreach($goods_list as $k=>$v){
            $goods_list[$k]['shop_price'] = $v['grade'.$grade_id.'_price'];
        }
        $this->assign('datalist',$goods_list);
        $this->assign("grade",$this->member['grade_id']);
        $this->display('Mobile@Goods:daili');
    }

    //tdk seo
    public function setSeo($data){

        $title = set_default($data,"title",C("SHARE_DEFAULT_TITLE"),true);
        $description = set_default($data,"description",C("SHARE_DEFAULT_DESC"));
        $keywords = set_default($data,"keywords",C("SHARE_DEFAULT_DESC"));


        $this->assign("seo_title",$title);
        $this->assign("seo_keywords",$keywords);
        $this->assign("seo_description",$description);

    }
    //share wechat
    public function setShare($data){

        $share_title = set_default($data,"title",C("SHARE_DEFAULT_TITLE"));
        $share_description = set_default($data,"description",C("SHARE_DEFAULT_DESC"));
        $share_img = set_default($data,"img",C("UPYUN_DOMAIN").C("SHARE_DEFAULT_IMG"));

        //如果没有头像用文章的图片
        if(!$share_img){
            //有身份的人用头像
            if($this->member['grade_id']>1){
                $share_img = $this->member['headimgurl'];
            }
        }

        $share_url = set_default($data,"url");
        if(!$share_url){
            $params = set_default($data,"params");
            $share_url  = $this->_get_share_url($params);
        }

        $this->assign("share_title",$share_title);
        $this->assign("share_url",$share_url);
        $this->assign("share_description",$share_description);
        $this->assign("share_img",$share_img);

    }

    /*
	 * 获取分享链接
	 */
    protected function _get_share_url($params=''){

        //拼接分享的网址
        $share_params = "from=sharelink&suid=".$this->uid;

        if($this->action == 'index'){
            $link = get_domain()."/mobile/".$this->contro;
        }else{
            $link = get_domain()."/mobile/".$this->contro."/".$this->action;
        }

        if($params){
            $share_url = $link."?".$params."&".$share_params;//有传参数的情况
        }else{
            $share_url = $link."?".$share_params;
        }

        return $share_url;
    }

    /*
	 * 操作失败
	 */
    public function error2($message="失败",$url=""){

        $seo_data = array(
            "title" => C("SITE_NAME"),
        );
        $this->setSeo($seo_data);

        $this->assign("message",$message);
        $this->assign("url",$url);
        $this->display("Common/error");
        exit;
    }

    public function success2($message="成功",$url=""){

        $seo_data = array(
            "title" => C("SITE_NAME"),
        );
        $this->setSeo($seo_data);

        $this->assign("message",$message);
        $this->assign("url",$url);
        $this->display("Common/success");
        exit;
    }


    /*
     * 生成推广二维码图片
     */
    public function makeshare($userinfo,$refresh=0){

        $uid = $userinfo['uid'];
        $headimgurl = $userinfo['headimgurl'];

        if(!$headimgurl){
            $headimgurl = C("UPYUN_DOMAIN").C("SHARE_DEFAULT_IMG");//如果没有获取到头像就用logo代替
        }

        $nickname = $userinfo['realname'] ? $userinfo['realname'] : $userinfo['nickname'];
        if(!$nickname){
            $nickname = C("SITE_NAME");
        }

        $clean_text = emoji_docomo_to_unified($nickname);
        $html = emoji_unified_to_html($clean_text);
        $nickname = strip_tags($html);

        $nickname = "".$nickname;

        if(!$uid){
            $uid = $userinfo['uid'];
        }
        $file = ROOT.'/upload/share/qr'.$uid.".jpg";//存储的文件名
        $pic_url = get_domain()."/upload/share/".$uid.".jpg";
        if(file_exists($file) && !$refresh){
            //如果文件存在 并且不需要更新
            return $pic_url;
        }

        //获取二维码图片
        $qrcode_pic = $this->qrcodeurl($uid,$refresh);
        if(!$qrcode_pic){
            return false;//生成二维码失败
        }

        /* $read_qrcode = file_get_contents($qrcode_pic);//读取二维码
        $erweima = imagecreatefromstring($read_qrcode);//把二维码载入画板
        $qwidth = imagesx($erweima);//二维码图片宽度
        $qheight = imagesy($erweima);//二维码的图片高度 */

        $grade = $userinfo['grade_id'] ? $userinfo['grade_id'] : 1;

        //$background_url = C("UPYUN_DOMAIN").C("QRCODE_GRADE".$grade);
        $background_url = C("QRCODE_GRADE".$grade);

        //$background_url = "http://qiniu.vlu2.cn/_upload_other_2018-09_07_806511536328822.jpg";

        $arr = array(
            array(
                'text' => qiniubase64url($userinfo['nickname']),
                'dx' => 0,
                'dy' => 180,
                'gravity' => 'North',
                'fontsize' => '600',
                'fill' => qiniubase64url('#ffffff'),
            ),
            array(
                'text' => qiniubase64url('ID: '.$uid),
                'dx' => 0,
                'dy' => 240,
                'gravity' => 'North',
                'fontsize' => '400',
                'fill' => qiniubase64url('#ffffff'),
            ),
            array(
                'image' => qiniubase64url($qrcode_pic),
                'dx' => 0,
                'dy' => -5,
                'gravity' => 'Center',
                'ws' => 0.43
            )
        );
        if(!empty($arr)) {
            $background_url .= "?watermark/3";
        }
        foreach($arr as $v) {
            if($v['text']) {
                $background_url .= "/text/{$v['text']}";
                if($v['fontsize']) {
                    $background_url .= "/fontsize/{$v['fontsize']}";
                }
                if($v['fill']) {
                    $background_url .= "/fill/{$v['fill']}";
                }
            }else{
                $background_url .= "/image/{$v['image']}";
            }
            $background_url .= "/dx/{$v['dx']}";
            $background_url .= "/dy/{$v['dy']}";
            $background_url .= "/gravity/{$v['gravity']}";
            if($v['ws']) {
                $background_url .= "/ws/{$v['ws']}";
            }

        }
        return $background_url;

        $read_backgroud = file_get_contents($background_url);//读取底图
        $background = imagecreatefromstring($read_backgroud);//把底图载入画板

        /*
         $dst_image：新建的图片
         $src_image：需要载入的图片
         $dst_x：设定需要载入的图片在新图中的x坐
         $dst_y：设定需要载入的图片在新图中的y坐标
         $src_x：设定载入图片要载入的区域x坐标
         $src_y：设定载入图片要载入的区域y坐标
         $dst_w：设定载入的原图的宽度（在此设置缩放）
         $dst_h：设定载入的原图的高度（在此设置缩放）
         $src_w：原图要载入的宽度
         $src_h：原图要载入的高度
        */
        imagecopyresampled($background,$erweima,167,308,0,0,193,193,$qwidth,$qheight);//把二维码放到背景图片上

        $read_headimgurl = curl($headimgurl);//读取头像
        $headimg = imagecreatefromstring($read_headimgurl);//头像写入画板

        $head_width = imagesx($headimg);
        $head_height = imagesy($headimg);//获取头像宽高

        //imagecopyresampled($background,$headimg,50,77,0,0,190,190,$head_width,$head_height);//把头像写在花瓣是

        $font = ROOT.'/Static/mobile/font/siyuan.ttf';//思源黑体

        $color= imagecolorallocate($background,255,255,255);//颜色

        if(mb_strlen($nickname)>22){
            $font_size = 16;
        }else if(mb_strlen($nickname)>18){
            $font_size = 19;
        }else if(mb_strlen($nickname)>16){
            $font_size = 20;
        }else{
            $font_size = 22;
        }
        imagettftext($background,$font_size,0,230,235,$color, $font,$nickname);//把名字写上去
        imagettftext($background,15,0,233,265,$color, $font,"我的ID:".$uid);
        //   imagettftext($background,22,0,350,178,$color, $font,$grade_name);//把等级写上去

        imagejpeg($background,$file,100);//最后一个参数是图片质量,保存图片到文件

        if(file_exists($file)){
            //如果文件存在 并且不需要更新
            return $pic_url;
        }

        return false;
    }


    //获取二维码地址
    public function qrcodeurl($uid,$refresh=0){

        /* $text = get_domain()."/mobile/login/register?refer=".$uid;//内容
        $pic_url = "http://qr.liantu.com/api.php?text=".$text;//图片网址
        return $pic_url; */

        $pic_url = get_domain()."/upload/qrcode/qr".$uid.".png";//图片网址
        $outfile = ROOT."/upload/qrcode/qr".$uid.".png";
        if(!file_exists($outfile) || $refresh){

            //qrcode($text, $outfile, $level = 1, $size = 8, $margin = 1,$saveandprint=false);

            $scene_id = "FENXIAO_UID_".$uid;
            $ticket_arr = $this->wechat->getQRCode($scene_id,2);//获取二维码ticket
            if(isset($ticket_arr['url'])){
                //getQRUrl($ticket)
                $text = $ticket_arr['url'];
                //return $pic_url = "http://qr.liantu.com/api.php?text=".$text;
                qrcode($text, $outfile, $level = 1, $size = 8, $margin = 1,$saveandprint=false);
            }

            if(!file_exists($outfile)){
                //不存在,生成失败
                return false;
            }
        }
        return $pic_url;
    }
}